// -----------------------------------------------------------------------
// <copyright file="Session.cs" company="Microsoft">
// Manage with sessions
// </copyright>
// -----------------------------------------------------------------------
namespace WebServer.BusinessLogic.Web
{
    using System;
    using System.Web;

    /// <summary>
    /// Class for working with sessions
    /// </summary>
    public class Session : ISession
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Session"/> class. 
        /// </summary>
        /// <param name="request">request object</param>
        public Session(Request request)
        {
            this.SessionKey = this.CreateSessionKey();
            this.DateCreated = DateTime.Now;
            this.LastAccessed = this.DateCreated;
            this.UniqueValidation = CreateUniqueValidation(request);
            this.IsAdmin = false;
        }

        /// <summary>
        /// Gets Date when the session was created
        /// </summary>
        public DateTime DateCreated { get; private set; }

        /// <summary>
        /// Gets Unique key of the session
        /// </summary>
        public string SessionKey { get; private set; }

        /// <summary>
        /// Gets or sets a value indicating whether	Indicates that logged into the session user has Administrator privileges
        /// </summary>
        public bool IsAdmin { get; set; }

        /// <summary>
        /// Gets or sets Last time of Session access
        /// </summary>
        public DateTime LastAccessed { get; set; }

        /// <summary>
        /// Gets Unique client validation. Consists of UserAgent + IP
        /// </summary>
        public string UniqueValidation { get; private set; }

        /// <summary>
        /// Saves UserAgent+IP
        /// </summary>
        /// <param name="request">request object</param>
        /// <returns>unique validator string</returns>
        public static string CreateUniqueValidation(Request request)
        {
            //// validate request before using it
            if (request == null)
            {
                return string.Empty;
            }

            string validationString = string.Format("{0}+{1}", request.UserAgent, request.UserIpAddress);
            return validationString;
        }

        /// <summary>
        /// Creates session key based on Guid
        /// </summary>
        /// <returns>session key string</returns>
        private string CreateSessionKey()
        {
            return Guid.NewGuid().ToString();
        }
    }

    public interface ISession
    {
        string SessionKey { get; }
    }
}